import axios from "axios";
import qsString from 'querystring'
import router from "../router";
import store from "../store";
// const http = axios.create({
//     baseURL: '/api'
// })
let baseURL = '/api'
//请求拦截
axios.interceptors.request.use(req => {
    //因为登录不需要验证token所以可以剔除登录判断
    if (req.url != baseURL +'/userlogin') {
        console.log(req.url);
        req.headers.authorization = store.getters.getUser.token
    }

    return req
})
//响应拦截
axios.interceptors.response.use(res => {
    //全局错误拦截
    if (res.data.msg == "请设置请求头,并携带验证字符串") {
        alert(res.data.msg);
        router.push('/login');
    } else if (res.data.msg == '登录已过期或访问权限受限') {
        alert(res.data.msg)
        router.push('/login');
    } else {
        return res.data
    }

})
// 独立封装get 方法
//Parmas====url 指调取的接口地址
//Parmas====params 参数
//ifFile判断是否有文件上传
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseURL + url, { params }).then((res) => {
            resolve(res);
        }).catch((err) => {
            reject(err);
        })
    })
}
export const post = (url, params = {}, isFile = false) => {
    //有文件上传
    let data = null
    if (isFile) {
        data = new FormData
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qsString.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(baseURL +url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
